package com.android.takagism.ui;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;

import com.android.takagism.R;
import com.android.takagism.utils.DbUtils;
import com.android.takagism.utils.UIHandler;

import java.util.Random;
import java.util.UUID;

public class AdminManageActivity extends AppCompatActivity {

    Random random = new Random();

    private Switch switch_deng;
    private TextView wen_shi_du_zzj1;
    private Switch switch_zi_dong_jia_shi;
    private Switch switch_zi_dong_tiao_wen;

    private SeekBar threshold_distance;
    private SeekBar threshold_illumination;
    private SeekBar threshold_vibration;

    private TextView threshold_distance_text;
    private TextView threshold_illumination_text;
    private TextView threshold_vibration_text;

    private Button save_all;

    private ContentValues contentValues = new ContentValues();
    private boolean has_value = false;
    private final int UPDATE = 12345;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_admin_manage);
        initViews();
        initViews2();
    }


    private void updateBefore() {
        SQLiteDatabase dbr = DbUtils.getInstance().getReadableDatabase();
        Cursor save_manage = dbr.query("save_manage", new String[]{
                "id", "deng", "wen_shi_du", "zi_dong_jia_shi", "zi_dong_tiao_wen"
                , "threshold_distance", "threshold_illumination", "threshold_vibration"
        }, "id = ?", new String[]{"0"}, null, null, null);

        System.out.println("获取之前" + contentValues);
        if (save_manage.moveToFirst()) {
            switch_deng.setChecked(save_manage.getInt(save_manage.getColumnIndex("deng")) == 1);
            wen_shi_du_zzj1.setText(save_manage.getString(save_manage.getColumnIndex("wen_shi_du")));
            switch_zi_dong_tiao_wen.setChecked(save_manage.getInt(save_manage.getColumnIndex("zi_dong_tiao_wen")) == 1);
            switch_zi_dong_jia_shi.setChecked(save_manage.getInt(save_manage.getColumnIndex("zi_dong_jia_shi")) == 1);
            int threshold_distance = save_manage.getInt(save_manage.getColumnIndex("threshold_distance"));
            this.threshold_distance.setProgress(threshold_distance);
            int threshold_illumination = save_manage.getInt(save_manage.getColumnIndex("threshold_illumination"));
            this.threshold_illumination.setProgress(threshold_illumination);
            int threshold_vibration = save_manage.getInt(save_manage.getColumnIndex("threshold_vibration"));
            this.threshold_vibration.setProgress(threshold_vibration);

            contentValues.put("deng", save_manage.getInt(save_manage.getColumnIndex("deng")));
            contentValues.put("wen_shi_du", save_manage.getString(save_manage.getColumnIndex("wen_shi_du")));
            contentValues.put("zi_dong_jia_shi", save_manage.getInt(save_manage.getColumnIndex("zi_dong_jia_shi")));
            contentValues.put("zi_dong_tiao_wen", save_manage.getInt(save_manage.getColumnIndex("zi_dong_tiao_wen")));
            contentValues.put("threshold_distance", threshold_distance);
            contentValues.put("threshold_illumination", threshold_illumination);
            contentValues.put("threshold_vibration", threshold_vibration);

            Log.d("TEST,updateBefore", (contentValues.toString()));
            has_value = true;
//            dbr.endTransaction();
        } else {
            int i;
            i = random.nextInt(threshold_distance.getMax() - threshold_distance.getMin()) + threshold_distance.getMin();
            contentValues.put("threshold_distance", i);

            i = random.nextInt(threshold_illumination.getMax() - threshold_illumination.getMin()) + threshold_illumination.getMin();
            contentValues.put("threshold_illumination", i);

            i = random.nextInt(threshold_vibration.getMax() - threshold_vibration.getMin()) + threshold_vibration.getMin();
            contentValues.put("threshold_vibration", i);

            contentValues.put("deng", 0);
            contentValues.put("wen_shi_du", "");
            contentValues.put("zi_dong_jia_shi", 0);
            contentValues.put("zi_dong_tiao_wen", 0);

            // 插入
            new Thread(new updateAfterTask()).start();
            System.out.println("不存在" + has_value);
        }
        uiHandler.sendEmptyMessage(UPDATE);
    }

    private Handler uiHandler;

    private void updateAfter() {
        System.out.println("插入成功updateAfter");
        SQLiteDatabase dbw = DbUtils.getInstance().getWritableDatabase();
        dbw.insert("save_manage", null, contentValues);
        has_value = true;
    }

    private void updateFinally() {
        System.out.println("修改成功updateFinally");
        SQLiteDatabase dbw = DbUtils.getInstance().getWritableDatabase();
        dbw.update("save_manage", contentValues, "id = ?", new String[]{"0"});
        System.out.println(contentValues);
    }

    private class updateAfterTask implements Runnable {
        @Override
        public void run() {
            updateAfter();
        }
    }

    private class updateBeforeTask implements Runnable {
        @Override
        public void run() {
            updateBefore();
        }
    }

    private class updateFinallyTask implements Runnable {
        @Override
        public void run() {
            updateFinally();
        }
    }

    @Override
    protected void onPause() {
        new Thread(new updateFinallyTask()).start();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        new Thread(new updateFinallyTask()).start();
        super.onDestroy();
    }

    private void initViews() {
        contentValues.put("id", "0");
        uiHandler = new UIHandler(Looper.myLooper()) {
            @Override
            public void handleMessage(@NonNull Message msg) {
                if (UPDATE == msg.what) {
                    int tmp = (int) contentValues.get("deng");
                    if (tmp == 1) {
                        switch_deng.setText(switch_deng.getTextOn());
                    } else {
                        switch_deng.setText(switch_deng.getTextOff());
                    }
                    tmp = (int) contentValues.get("zi_dong_jia_shi");
                    if (tmp == 1) {
                        switch_zi_dong_jia_shi.setText(switch_zi_dong_jia_shi.getTextOn());
                    } else {
                        switch_zi_dong_jia_shi.setText(switch_zi_dong_jia_shi.getTextOff());
                    }
                    tmp = (int) contentValues.get("zi_dong_tiao_wen");
                    if (tmp == 1) {
                        switch_zi_dong_tiao_wen.setText(switch_zi_dong_tiao_wen.getTextOn());
                    } else {
                        switch_zi_dong_tiao_wen.setText(switch_zi_dong_tiao_wen.getTextOff());
                    }
                    wen_shi_du_zzj1.setText((String) contentValues.get("wen_shi_du"));
                    threshold_distance_text.setText(threshold_distance.getProgress() + " cm");
                    threshold_illumination_text.setText(threshold_illumination.getProgress() + " lx");
                    threshold_vibration_text.setText(threshold_vibration.getProgress() + " unit");
                }
                super.

                        handleMessage(msg);
            }
        }

        ;

        switch_deng = findViewById(R.id.switch_deng);

        wen_shi_du_zzj1 = findViewById(R.id.wen_shi_du_zzj1);

        switch_zi_dong_jia_shi = findViewById(R.id.switch_zi_dong_jia_shi);

        switch_zi_dong_tiao_wen = findViewById(R.id.switch_zi_dong_tiao_wen);

        threshold_distance = findViewById(R.id.threshold_distance);

        threshold_illumination = findViewById(R.id.threshold_illumination);

        threshold_vibration = findViewById(R.id.threshold_vibration);

        threshold_distance_text = findViewById(R.id.threshold_distance_text);

        threshold_illumination_text = findViewById(R.id.threshold_illumination_text);

        threshold_vibration_text = findViewById(R.id.threshold_vibration_text);

        switch_deng.setTextOn("关灯");
        switch_deng.setTextOff("开灯");

        switch_zi_dong_jia_shi.setTextOn("关闭自动加湿");
        switch_zi_dong_jia_shi.setTextOff("自动加湿");

        switch_zi_dong_tiao_wen.setTextOff("自动调温");
        switch_zi_dong_tiao_wen.setTextOn("关闭自动调温");

        threshold_distance.setMax(1500);
        threshold_distance.setMin(20);

        threshold_illumination.setMax(2000);
        threshold_illumination.setMin(50);

        threshold_vibration.setMax(100);
        threshold_vibration.setMin(1);

        // 先修改
//        new Thread(new updateBeforeTask()).start();
        updateBefore();
        // 设置灯


        switch_deng.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    switch_deng.setText(switch_deng.getTextOn());
                    contentValues.put("deng", 1);
                } else {
                    switch_deng.setText(switch_deng.getTextOff());
                    contentValues.put("deng", 0);
                }
            }
        });

        // 湿度

        switch_zi_dong_jia_shi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    switch_zi_dong_jia_shi.setText(switch_zi_dong_jia_shi.getTextOn());
                    contentValues.put("zi_dong_jia_shi", 1);
                } else {
                    switch_zi_dong_jia_shi.setText(switch_zi_dong_jia_shi.getTextOff());
                    contentValues.put("zi_dong_jia_shi", 0);
                }
            }
        });

        // 温度

        switch_zi_dong_tiao_wen.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    switch_zi_dong_tiao_wen.setText(switch_zi_dong_tiao_wen.getTextOn());
                    contentValues.put("zi_dong_tiao_wen", 1);
                } else {
                    switch_zi_dong_tiao_wen.setText(switch_zi_dong_tiao_wen.getTextOff());
                    contentValues.put("zi_dong_tiao_wen", 0);
                }
            }
        });

        /*
         阈值调节
         */

        // 距离


        threshold_distance.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                threshold_distance_text.setText(threshold_distance.getProgress() + " cm");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                contentValues.put("threshold_distance", threshold_distance.getProgress());
            }
        });

        // 光照

//        if (!has_value) {
//            i = random.nextInt(threshold_illumination.getMax() - threshold_illumination.getMin()) + threshold_illumination.getMin();
//            threshold_illumination.setProgress(i);
//            contentValues.put("threshold_illumination",i);
//        }


        threshold_illumination.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                threshold_illumination_text.setText(threshold_illumination.getProgress() + " lx");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                contentValues.put("threshold_illumination", threshold_illumination.getProgress());
                Log.d("TEST", contentValues.toString());
            }
        });


        // 振动

//        if (!has_value) {
//            i = random.nextInt(threshold_vibration.getMax() - threshold_vibration.getMin()) + threshold_vibration.getMin();
//            threshold_vibration.setProgress(i);
//            contentValues.put("threshold_vibration",i);
//        }

        threshold_vibration.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                threshold_vibration_text.setText(threshold_vibration.getProgress() + " unit");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                contentValues.put("threshold_vibration", threshold_vibration.getProgress());
            }
        });


//        new Thread(new updateAfterTask()).start();
    }

    private void initViews2(){
        save_all = findViewById(R.id.save_all);
        save_all.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateFinally();
                AlertDialog.Builder builder = new AlertDialog.Builder(AdminManageActivity.this);
                builder.setTitle("提示")
                        .setMessage("保存成功！")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        })
                .create().show();
            }
        });
    }
}